﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using Library.WebControls.Ds;

namespace Library.WebControls {
	public class SimpleItemBoundEventArgs<T> : EventArgs where T : IDataItemContainer {
		private readonly bool _canGetValue;
		private readonly DataSourceWrapper.DataItemWraper _itemWrapper;
		private readonly SpListItem _listItem;
		internal SimpleItemBoundEventArgs(DataSourceWrapper.DataItemWraper itemWraper) {
			_itemWrapper = itemWraper;
			_canGetValue = true;
		}
		internal SimpleItemBoundEventArgs(DataSourceWrapper.DataItemWraper itemWraper, T item) {
			Item = item;
			_itemWrapper = itemWraper;
			_canGetValue = true;
		}
		internal SimpleItemBoundEventArgs(SpListItem listItem, T item) {
			Item = item;

			_listItem = listItem;
			_canGetValue = true;
		}
		public SimpleItemBoundEventArgs(T item) {
			Item = item;
		}

		public T Item { get; private set; }
		public virtual object GetValue(string fieldName) {
			if (_listItem != null) return _listItem.Value;
			if (String.IsNullOrEmpty(fieldName)) throw new ArgumentNullException("Property " + fieldName + " not found");
			if (_canGetValue) {
				return _itemWrapper.GetPropertyValue(fieldName);
			}
			var ps = System.ComponentModel.TypeDescriptor.GetProperties(Item.DataItem);

			var p = ps.Find(fieldName, false);
			if (p == null) throw new Exception("Property " + fieldName + " not found");
			return p.GetValue(Item.DataItem);
		}
	}
}
